package com.lingyun.mqttserver.service.impl;

import jakarta.annotation.Resource;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;


@Service
public class MqttMessageService {

    @Resource(name = "mqttOutputChannel")
    private MessageChannel mqttOutputChannel;


    /**
     * 发送MQTT消息
     * @param topic 主题
     * @param payload 消息内容
     * @return 是否发送成功
     */
    public boolean sendMessage(String topic, String payload) {
        return mqttOutputChannel.send(MessageBuilder.withPayload(payload)
                .setHeader("mqtt_topic", topic)
                .setHeader("mqtt_qos", 1)
                .build());
    }
    
    /**
     * 发送MQTT消息，指定QoS级别
     * @param topic 主题
     * @param payload 消息内容
     * @param qos QoS级别
     * @return 是否发送成功
     */
    public boolean sendMessage(String topic, String payload, int qos) {
        return mqttOutputChannel.send(MessageBuilder.withPayload(payload)
                .setHeader("mqtt_topic", topic)
                .setHeader("mqtt_qos", qos)
                .build());
    }
    
    /**
     * 发送设备控制命令
     * @param hardwareAddress 设备ID
     * @param command 命令内容
     * @return 是否发送成功
     */
    public boolean sendDeviceCommand(String hardwareAddress, String command) {
        String topic = hardwareAddress + "/command";
        return sendMessage(topic, command, 1); // 设备控制命令使用QoS 1确保可靠送达
    }

    /**
     * 发送MQTT保留消息
     * @param topic 主题
     * @param payload 消息内容
     * @param retained 是否设置为保留消息
     * @return 是否发送成功
     */
    public boolean sendMessage(String topic, String payload, boolean retained) {
        return mqttOutputChannel.send(MessageBuilder.withPayload(payload)
                .setHeader("mqtt_topic", topic)
                .setHeader("mqtt_qos", 1)
                .setHeader("mqtt_retained", retained) // 设置保留消息标志
                .build());
    }
}
